import schedule from "node-schedule";
import {config} from "../config/index.js";
import blockchainPriceDao from "../Dao/blockchain_price.js";
import {getCoinPriceSpider} from "../utils/blockchainUtils.js";
import {getPriceCoinPair, getPriceUSDT} from "../api/api_okx/useOkx.js";

export const timer_coin_price = async () => {
  // 启动一个定时任务 1小时执行一次 立即执行
  // const TIME_GAP = '1 * * * *'; // 每小时第一分钟执行
  const TIME_GAP = `*/${config.TIMER_GAP} * * * *`; // 每隔config.TIMER_GAP（5）分钟执行一次
  const job = schedule.scheduleJob(TIME_GAP, async function () {

    console.log('开始查询币种价格...');
    // 获取所有需要查询的币种
    const coins = await getCoinList();
    // console.log(coins, 'coins');
    // 查询价格
    const prices = await getCoinPrice(coins);
    // console.log(prices, 'prices');
    // 更新数据库
    await updateCoinPrice(prices);
  });
};

// 获取所有需要查询的币种
const getCoinList = async () => {
  let coins = await blockchainPriceDao.findAll();
  return coins;
};

// 查询价格
const getCoinPrice = async (coins) => {
  let prices = [];
  for (let i = 0; i < coins.length; i++) {
    let item = coins[i];
    let id = item.id;
    let name = item.name;
    let unicode = item.unicode;
    // 这个采用无头浏览器方式
    // let platform = item.platform;
    // let selector = item.selector;
    // let price = await getCoinPriceSpider(unicode, platform, selector);
    // if (!price.result) {
    //   continue;
    // }
    // 采用api方式
    let price = {price:0};
    if(item.name === 'USDT') {
      price.price = await getPriceUSDT();
    } else {
      price.price = await getPriceCoinPair(`${unicode.split('-')[0].toUpperCase()}-USDT`);
    }
    if(!price.price) {
      continue;
    }
    prices.push({id, price: price.price, name});
    // console.log(`查询到币种: ${name} 价格为: ${price.price}`);
  }
  return prices;
};

// 更新币种价格
const updateCoinPrice = async (prices) => {
  for (let i = 0; i < prices.length; i++) {
    let item = prices[i];
    let id = item.id;
    let name = item.name;
    let price = item.price;
    await blockchainPriceDao.updatePrice(id, price);
    console.log(`更新币种: ${name} 价格为: ${price}`);
  }
};

timer_coin_price();
